<template>
  <div class="container">
    <div class="form-container">
      <div class="header">{{ isEdited ? "试题修改" : "试题录入" }}</div>
      <el-form
        ref="form"
        :model="formData"
        label-width="100px"
        class="form"
        :rules="rules"
      >
        <el-form-item label="学科:" size="small" prop="subjectID">
          <el-select
            v-model="formData.subjectID"
            placeholder="请选择"
            style="width: 400px"
            @change="subjectChange"
          >
            <el-option
              v-for="item in subList"
              :key="item.id"
              :label="item.subjectName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="目录:" size="small" prop="catalogID">
          <el-select
            v-model="formData.catalogID"
            placeholder="请选择"
            style="width: 400px"
          >
            <el-option
              v-for="(item, index) in dirList"
              :key="index"
              :label="item.directoryName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业:" size="small" prop="enterpriseID">
          <el-select
            v-model="formData.enterpriseID"
            placeholder="请选择活动区域"
            style="width: 400px"
          >
            <el-option
              v-for="item in companys"
              :key="item.number"
              :value="item.id"
              :label="item.company"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市:" size="small" required class="citysel">
          <el-form-item class="city-item" prop="province">
            <el-select
              v-model="formData.province"
              placeholder="请选择"
              style="width: 195px"
              @change="cityChange"
              size="small"
            >
              <el-option
                v-for="(item, index) in citys"
                :label="item"
                :key="index"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="city-item city-item2" prop="city">
            <el-select
              v-model="formData.city"
              placeholder="请选择"
              style="width: 195px"
              size="small"
            >
              <el-option
                v-for="(item, index) in areas"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form-item>
        <el-form-item label="方向:" size="small" prop="direction">
          <el-select
            v-model="formData.direction"
            placeholder="请选择"
            style="width: 400px"
          >
            <el-option
              v-for="(item, index) in direction"
              :label="item"
              :key="index"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="题型:" size="small" prop="questionType">
          <el-radio-group v-model="formData.questionType" style="width: 400px">
            <el-radio
              v-for="(item, index) in questionType"
              :key="index"
              :label="item.value + ''"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度:" size="small" prop="difficulty">
          <el-radio-group v-model="formData.difficulty" style="width: 400px">
            <el-radio
              v-for="(item, index) in difficulty"
              :key="index"
              :label="item.value + ''"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题干:" prop="question">
          <quill-editor
            ref="myLQuillEditorStem"
            v-model="formData.question"
            :options="editorOption"
            class="editor"
            @click.native="handleEditStemAblequestion"
          >
          </quill-editor>
        </el-form-item>
        <!-- 单选 -->
        <!-- v-if="formData.questionType === '单选'" -->
        <el-form-item label="选项" v-if="isOne">
          <el-radio-group v-model="radio" style="width: 400px">
            <div
              class="option"
              v-for="(item, index) in questionArr"
              :key="index"
              :style="{ margin: index < multNumer ? '10px 0 ' : '0' }"
            >
              <template v-if="index < multNumer">
                <el-radio :label="index">{{ item.code }}:</el-radio>
                <el-input
                  size="small"
                  style="width: 240px"
                  v-model="item.title"
                ></el-input>
                <!-- 上传图片组件 -->
                <ElUploadVue :item="item"></ElUploadVue>
              </template>
            </div>
          </el-radio-group>
        </el-form-item>
        <!-- 多选 -->
        <el-form-item label="选项" v-if="isMult">
          <el-checkbox-group v-model="checkList" style="width: 400px">
            <div
              class="option"
              v-for="(item, index) in questionArr"
              :key="index"
              :style="{ margin: index < multNumer ? '10px 0 ' : '0' }"
            >
              <template v-if="index < multNumer">
                <el-checkbox :label="index">{{ item.code }}:</el-checkbox>
                <el-input
                  size="small"
                  style="width: 240px"
                  v-model="item.title"
                ></el-input>
                <!-- 上传图片组件 -->
                <ElUploadVue :item="item"></ElUploadVue>
              </template>
            </div>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item>
          <el-button
            type="danger"
            size="small"
            :disabled="isOne"
            @click="addItem"
            v-if="formData.questionType !== '3'"
            >+增加选项与答案</el-button
          >
        </el-form-item>
        <el-form-item label="解析视频:" size="small">
          <el-input v-model="formData.videoURL"></el-input>
        </el-form-item>
        <el-form-item label="答案解析:" size="small" prop="answer">
          <quill-editor
            ref="myLQuillEditorAnaly"
            v-model="formData.answer"
            :options="editorOption"
            class="editor"
            @click.native="handleEditAnalyAblequestion"
          >
          </quill-editor>
        </el-form-item>
        <el-form-item label="题目备注:" size="small">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
            v-model="formData.remarks"
            style="width: 400px"
            class="form-textarea"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="试题标签:" size="small">
          <el-select
            v-model="formData.tags"
            placeholder="请选择试题标签"
            style="width: 400px"
            multiple
            filterable
            allow-create
            default-first-option
          >
            <el-option
              v-for="(item, index) in tagList"
              :key="index"
              :label="item.tagName"
              :value="item.tagName"
            >
            </el-option>
            <!-- <el-option label="大数据" value="shanghai"></el-option>
            <el-option label="phython" value="beijing"></el-option> -->
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="small"
            @click="sendForm"
            v-if="!isEdited"
            >确认提交</el-button
          >
          <el-button v-else type="success" size="small" @click="sendForm"
            >确认修改</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'

// 导入学科列表接口
import { list as getSubList } from '@/api/hmmm/subjects.js'
// 目录列表
import { list as getDirList } from '@/api/hmmm/directorys'
// 导入公司列表
import { list as getCompanyList } from '@/api/hmmm/companys.js'
// 导入获取城市列表
import { provinces as getCitys, citys as getAreas } from '@/api/hmmm/citys.js'
// 导入方向
import { direction, difficulty, questionType, questionArr } from '@/api/hmmm/constants.js'
// 引入头像组件
import ElUploadVue from '../components/elUpload.vue'
// 引入新增题目接口
import { add as addQuestion, detail as questionDetail, update as updateQuestion } from '@/api/hmmm/questions'

// const testData = {
//   subjectID: 8,
//   catalogID: 16,
//   enterpriseID: 18,
//   province: '石家庄市',
//   city: '裕华区',
//   direction: '互联网金融',
//   questionType: '2',
//   difficulty: '2',
//   question: '<p>121212</p>',
//   options: [
//     { code: 'D', title: '', img: '', isRight: false },
//     { code: 'C', title: '', img: '', isRight: false },
//     { code: 'B', title: '1212212', img: '', isRight: true },
//     { code: 'A', title: '1212', img: '', isRight: true }
//   ],
//   videoURL: '1211111111',
//   answer: '<p>112121212121212</p>',
//   remarks: '12121212121212',
//   tags: '11111'
// }
// const data2 = {
//   subjectID: 25,
//   catalogID: 16,
//   enterpriseID: 18,
//   province: '北京市',
//   city: '东城区',
//   direction: 'o2o',
//   questionType: '1',
//   difficulty: '1',
//   question: '<p>121212</p>',
//   options: [
//     { code: 'A', title: '121212', img: '', isRight: true },
//     { code: 'B', title: '1212', img: '', isRight: false },
//     { code: 'C', title: '1212', img: '', isRight: false },
//     { code: 'D', title: '1212', img: '', isRight: false }
//   ],
//   videoURL: '1212',
//   answer: '<p>121212</p>',
//   remarks: '1212',
//   tags: ['12']
// }

// 工具栏配置项
const toolbarOptions = [
  // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
  ['bold', 'italic', 'underline', 'strike'],
  // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  [{ list: 'ordered' }, { list: 'bullet' }],
  // 引用  代码块-----['blockquote', 'code-block']
  ['blockquote'],
  // 链接、图片、视频-----['link', 'image', 'video']
  ['code-block', 'image', 'link']
]
export default {
  data () {
    return {
      // 富文本相关
      editorOption: {
        modules: {
          toolbar: toolbarOptions
        },
        theme: 'snow',
        placeholder: '请输入正文'
      },
      formData: this.createDefaultForm(),
      subList: [], // 学科列表
      dirList: [], // 目录列表
      companys: [], // 公司列表
      citys: [], // 城市列表
      areas: [], // 区域列表
      direction, // 方向
      difficulty, // 试题难度
      questionType, // 试题类型
      checkList: [], // 多选题选中列表
      questionArr, // 储存选项的数组
      radio: '', // 单选选中的项
      multNumer: 4, // 多选的选项个数
      tagList: [], // 标签列表
      rules: {
        subjectID: [{ required: true, message: '请选择学科' }],
        catalogID: [{ required: true, message: '请选择目录' }],
        enterpriseID: [{ required: true, message: '请选择企业' }],
        province: [{ required: true, message: '请选择地区' }],
        direction: [{ required: true, message: '请选择方向' }],
        question: [{ required: true, message: '请输入题干' }],
        answer: [{ required: true, message: '请输入答案解析' }],
        videoURL: [{ required: true, message: '请输入解析视频地址' }],
        questionType: [{ required: true, message: '请输入题型' }],
        difficulty: [{ required: true, message: '请输入难度' }]
      },
      timer: null,
      qillInitStem: true,
      qillInitAnaly: true
    }
  },
  async created () {
    // 清空列表
    this.questionArr = this.questionArr.map(item => ({ code: item.code, title: '', img: '', isRight: '' }))
    // // 编辑状态 回到顶部
    // this.isEdited && this.backtop()
    // 获取学科列表
    this.getSubListFn()
    // 获取公司列表
    this.getCompanyListFn()
    // 获取城市列表
    this.getCitysFn()
    // 编辑状态 获取题目详情回显
    this.isEdited && this.getQuestionsDetail()
  },
  mounted () {
    // 富文本失效
    this.$refs.myLQuillEditorStem.quill.enable(false)
    this.$refs.myLQuillEditorAnaly.quill.enable(false)
  },
  components: {
    quillEditor,
    ElUploadVue
  },
  methods: {
    // 获取学科列表
    async getSubListFn () {
      // 获取学科列表
      const res = await getSubList()
      this.subList = res.data.items
    },
    // 获取目录列表
    async getDirListFn () {
      const res = await getDirList({
        subjectID: this.formData.subjectID
      })
      this.dirList = res.data.items
      // console.log(this.dirList)
    },
    // 获取公司列表
    async getCompanyListFn () {
      const res = await getCompanyList()
      this.companys = res.data.items
    },
    getCitysFn () {
      this.citys = getCitys()
    },
    cityChange () {
      this.formData.city = ''
      // 获取区数据
      // console.log(this.formData.province)
      this.getAreasFn()
    },
    // 获取区域列表
    getAreasFn () {
      this.areas = getAreas(this.formData.province)
    },
    // 学科改变
    subjectChange () {
      // 清空目录
      this.formData.catalogID = ''
      // 获取目录
      this.getDirListFn()
    },
    // 点击添加
    addItem () {
      // 多选的数量+1
      if (this.multNumer > 25) return
      this.multNumer++
    },
    // 点击提交表单
    async sendForm () {
      this.$refs.form.validate().then(async () => {
        // console.log(this.formData.questionType)
        // 表单验证成功后  单选题
        if (this.formData.questionType === '1') {
          // 重置题目的isRight
          this.resetIsRight()
          // 截取所需的数组

          const sendArr = this.questionArr.slice(0, this.multNumer)
          // 题目列表中对应选中
          sendArr[this.radio].isRight = 1
          // 放到表单中
          this.formData.options = sendArr
        }
        // 多选题
        if (this.formData.questionType === '2') {
          // 重置题目的isRight
          this.resetIsRight()
          // 截取所需数组
          const sendArr = this.questionArr.slice(0, this.multNumer)
          console.log(sendArr)
          // 题目列表中对应选中
          // console.log(this.checkList)
          this.checkList.forEach(item => {
            sendArr[item].isRight = 1
          })
          // 放到表单中
          this.formData.options = sendArr
        }
        // 请求成功
        //  修改状态

        if (this.isEdited) {
          console.log(JSON.stringify(this.formData.options))
          // 请求修改的接口
          const res = await updateQuestion({ ...this.formData, tags: this.formData.tags.join(',') })
          if (res.status === 200) {
            this.$message.success('修改成功')
            // 跳转到基础题库
            this.$router.push('/questions/list')
          }
          return
        }

        const res = await addQuestion(this.formData)
        if (res.status === 200) {
          this.$message.success('新增成功')
          // 跳转到基础题库
          this.$router.push('/questions/list')
        }
      })
    },
    // 重置表单
    createDefaultForm () {
      return {
        subjectID: '', // 学科ID
        catalogID: '', // 目录ID
        enterpriseID: '', // 公司ID
        province: '', // 城市
        city: '', // 区域
        direction: '', // 方向
        questionType: '1',
        difficulty: '1',
        question: '', // 题干
        options: [], // 选项,
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: ''// 试题标签
      }
    },
    // 重置题目的isRight
    resetIsRight () {
      this.questionArr = this.questionArr.map(item => ({ ...item, isRight: 0 }))
    },
    // 获取题目详情
    async getQuestionsDetail () {
      const { data } = await questionDetail({ id: this.$route.query.id, isNext: false })
      // 数据回显
      const options = data.options.sort((a, b) => a.code.localeCompare(b.code))// 选项

      // arr.sort((a, b) => a.code.localeCompare(b.code));
      // console.log(options)
      // 从questionArr中删除前n项替换为options
      // 重置questionArr
      this.questionArr.splice(0, options.length, ...options)
      // 更新multNumer
      this.multNumer = options.length
      // 判断是多选还单选
      this.formData.questionType = data.questionType
      // console.log(data, options, this.questionArr, this.questionType, this.isMult)
      if (this.formData.questionType === '2') { // 多选
        // this.checkList = options.
        options.forEach((item, index) => {
          if (item.isRight) { // 选中的
            this.checkList.push(index)
          }
        })
        // console.log(this.checkList)
      }
      // 单选
      if (this.formData.questionType === '1') {
        options.forEach((item, index) => {
          if (item.isRight) { // 选中的
            this.radio = index
          }
        })
      }
      // 设置表单数据为详情数据
      this.formData = { ...data, tags: data.tags.split(',') }
      // console.log(this.formData)
      this.$nextTick(() => {
        // 回到顶部
        this.backtop()
        // 题干和解析失去焦点
      })
    },
    // 题干失焦
    handleEditStemAblequestion () {
      // this.$refs.myLQuillEditorStem.quill.enable(false)
      // this.$refs.myLQuillEditorAnaly.quill.enable(false)
      if (this.qillInitStem) {
        this.$refs.myLQuillEditorStem.quill.enable(true)
        this.$refs.myLQuillEditorStem.quill.focus()
        this.qillInitStem = false
      }
    },
    // 解析失焦
    handleEditAnalyAblequestion () {
      // this.$refs.myLQuillEditorStem.quill.enable(false)
      // this.$refs.myLQuillEditorAnaly.quill.enable(false)
      if (this.qillInitAnaly) {
        this.$refs.myLQuillEditorAnaly.quill.enable(true)
        this.$refs.myLQuillEditorAnaly.quill.focus()
        this.qillInitStem = false
      }
    },
    // 回到顶部
    backtop () {
      document.documentElement.scrollTop = document.body.scrollTop = 0
    }
  },
  computed: {
    isEdited () {
      return !!this.$route.query.id
    },
    // 多选
    isMult () {
      return this.formData.questionType === '2'
    },
    // 单选
    isOne () {
      return this.formData.questionType === '1'
    }
  },
  watch: {
    '$route.query.id' (val) {
      // 回显
      val && this.getQuestionsDetail()
      // 刷新页面
      this.$router.go(0)
    }

  }
}
</script>

<style  lang='scss'>
.container {
  box-sizing: border-box;
  padding: 20px;
  padding-left: 15px;
  .citysel {
    // display: flex;
    .city-item {
      display: inline-block;
    }
    .city-item2 {
      margin-left: 10px;
    }
  }

  .ql-editor {
    height: 200px;
  }

  .option {
    display: flex;
    align-items: center;
    margin: 10px 0;
    .el-radio {
      margin-right: 10px;
    }
    .el-checkbox {
      margin-right: 10px;
    }
    // .el-input {
    //   margin-left: 10px;
    // }
  }

  .form-container {
    background: #fff;
  }
  .header {
    padding: 18px 20px;
    border-bottom: 1px solid #ccc;
  }
  .form {
    padding-top: 15px;
    padding-left: 70px;
    padding-bottom: 20px;
    padding-right: 20px;
    .form-textarea {
      .el-textarea__inner {
        height: 100px;
      }
    }
  }
}
</style>
